#!/bin/bash

# =============================================================================
# Docker镜像加速器测试和修复脚本
# 2025年1月最新可用镜像源
# =============================================================================

set -euo pipefail

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

# 2025年可用的Docker镜像加速器列表
MIRROR_LIST=(
    "https://docker.1panel.live"
    "https://docker.1ms.run"
    "https://dytt.online"
    "https://docker-0.unsee.tech"
    "https://lispy.org"
    "https://docker.xiaogenban1993.com"
    "https://666860.xyz"
    "https://hub.rat.dev"
    "https://docker.m.daocloud.io"
    "https://demo.52013120.xyz"
    "https://proxy.vvvv.ee"
    "https://registry.cyou"
)

# 当前配置的镜像列表（可能失效的）
OLD_MIRRORS=(
    "https://registry.cn-hangzhou.aliyuncs.com"
    "https://mirror.ccs.tencentyun.com"
    "https://hub-mirror.c.163.com"
    "https://docker.mirrors.ustc.edu.cn"
    "https://f1361db2.m.daocloud.io"
)

test_mirror() {
    local mirror_url="$1"
    local timeout=5
    
    log_info "测试镜像源: $mirror_url"
    
    # 测试基本连通性
    if curl -I --connect-timeout $timeout --max-time $timeout "$mirror_url/v2/" >/dev/null 2>&1; then
        log_success "✅ $mirror_url - 可用"
        return 0
    else
        log_warning "❌ $mirror_url - 不可用"
        return 1
    fi
}

test_all_mirrors() {
    local available_mirrors=()
    
    log_info "开始测试所有镜像加速器..."
    echo ""
    
    log_info "=== 测试当前配置的镜像源 ==="
    for mirror in "${OLD_MIRRORS[@]}"; do
        if test_mirror "$mirror"; then
            available_mirrors+=("$mirror")
        fi
    done
    
    echo ""
    log_info "=== 测试2025年新镜像源 ==="
    for mirror in "${MIRROR_LIST[@]}"; do
        if test_mirror "$mirror"; then
            available_mirrors+=("$mirror")
        fi
    done
    
    echo ""
    log_info "可用镜像源总数: ${#available_mirrors[@]}"
    
    if [ ${#available_mirrors[@]} -eq 0 ]; then
        log_error "没有找到可用的镜像加速器！"
        return 1
    fi
    
    # 返回可用镜像列表
    printf '%s\n' "${available_mirrors[@]}"
}

backup_docker_config() {
    local backup_file="/etc/docker/daemon.json.backup.$(date +%Y%m%d_%H%M%S)"
    
    if [ -f "/etc/docker/daemon.json" ]; then
        log_info "备份当前Docker配置到: $backup_file"
        cp /etc/docker/daemon.json "$backup_file"
    fi
}

update_docker_daemon() {
    local available_mirrors=("$@")
    
    if [ ${#available_mirrors[@]} -eq 0 ]; then
        log_error "没有可用的镜像源，无法更新配置"
        return 1
    fi
    
    log_info "更新Docker daemon配置..."
    
    # 备份现有配置
    backup_docker_config
    
    # 创建新的daemon.json
    mkdir -p /etc/docker
    
    cat > /etc/docker/daemon.json << EOF
{
  "registry-mirrors": [
$(printf '    "%s"' "${available_mirrors[0]}"; printf ',\n    "%s"' "${available_mirrors[@]:1}")
  ],
  "log-driver": "json-file",
  "log-opts": {
    "max-size": "10m",
    "max-file": "3"
  },
  "storage-driver": "overlay2",
  "live-restore": true,
  "userland-proxy": false,
  "no-new-privileges": true,
  "default-ulimits": {
    "nofile": {
      "Name": "nofile",
      "Hard": 65536,
      "Soft": 65536
    }
  },
  "features": {
    "buildkit": true
  }
}
EOF
    
    log_success "Docker daemon配置已更新"
    log_info "新配置中包含 ${#available_mirrors[@]} 个可用镜像源"
}

restart_docker() {
    log_info "重启Docker服务..."
    
    systemctl daemon-reload
    systemctl restart docker
    
    # 等待Docker启动
    sleep 5
    
    if systemctl is-active --quiet docker; then
        log_success "Docker服务重启成功"
    else
        log_error "Docker服务重启失败"
        return 1
    fi
}

verify_configuration() {
    log_info "验证新配置..."
    
    # 检查docker info输出
    if docker info | grep -A 20 "Registry Mirrors" | grep -q "https://"; then
        log_success "镜像加速器配置验证成功"
        
        echo ""
        log_info "当前配置的镜像加速器:"
        docker info | grep -A 20 "Registry Mirrors" | grep "https://"
        
        return 0
    else
        log_error "镜像加速器配置验证失败"
        return 1
    fi
}

test_docker_pull() {
    log_info "测试Docker镜像拉取..."
    
    # 测试拉取一个小镜像
    if timeout 60 docker pull hello-world >/dev/null 2>&1; then
        log_success "Docker镜像拉取测试成功"
        return 0
    else
        log_warning "Docker镜像拉取测试失败，但配置可能仍然有效"
        return 1
    fi
}

main() {
    echo "==============================================================================="
    echo "🚀 Docker镜像加速器诊断和修复工具 v1.0"
    echo "==============================================================================="
    echo ""
    
    # 检查是否以root权限运行
    if [[ $EUID -ne 0 ]]; then
        log_error "此脚本需要root权限运行"
        exit 1
    fi
    
    # 检查Docker是否安装
    if ! command -v docker &> /dev/null; then
        log_error "Docker未安装"
        exit 1
    fi
    
    # 测试所有镜像源
    log_info "开始诊断Docker镜像加速器问题..."
    echo ""
    
    # 获取可用镜像列表
    mapfile -t available_mirrors < <(test_all_mirrors)
    
    if [ ${#available_mirrors[@]} -eq 0 ]; then
        log_error "所有镜像源都不可用，请检查网络连接"
        exit 1
    fi
    
    echo ""
    log_info "找到 ${#available_mirrors[@]} 个可用镜像源，开始更新配置..."
    
    # 更新Docker daemon配置
    update_docker_daemon "${available_mirrors[@]}"
    
    # 重启Docker服务
    restart_docker
    
    # 验证配置
    verify_configuration
    
    # 测试拉取
    echo ""
    test_docker_pull
    
    echo ""
    echo "==============================================================================="
    log_success "🎉 Docker镜像加速器修复完成！"
    echo "==============================================================================="
    echo ""
    log_info "现在可以尝试重新拉取Dify镜像:"
    echo "   cd /root/dify"
    echo "   docker compose -f docker-compose.production.yml pull"
    echo "   docker compose -f docker-compose.production.yml up -d"
    echo ""
}

# 执行主函数
main "$@" 